﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IRepository.WareHouse;
using ProTrack.Utility;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;
using ProTrack.IServices.Stock;
using ProTrack.Report;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 生产领料服务接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrderProductPickController : Controller
    {
        public OrderProductPickController(IOrderProductPickServices services, LogHelper LogHelper) 
        {
            Services = services;
            this.LogHelper = LogHelper;
        }
        private IOrderProductPickServices Services { get; }
        private LogHelper LogHelper { get; }

        /// <summary>
        /// 获取所有生产领料信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("生产领料-获取所有", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据页码，页大小，工艺路线编号，工艺路线名称，是否启用获取生产领料信息方法
        /// </summary>
        /// <param name="PageIndex">页码</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="Number">生产领料编号</param>
        /// <param name="PickDate">领料日期</param>
        /// <param name="WarehouseName">领料仓库</param>
        /// <param name="EmployeesName">经办人</param>
        /// <param name="Status">订单状态</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string PickDate, [FromQuery] string WarehouseName, [FromQuery] string EmployeesName, [FromQuery] int? Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAsync(PageIndex, PageSize, Number ?? "", PickDate ?? "", WarehouseName ?? "", EmployeesName ?? "",Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number ?? "", PickDate, WarehouseName ?? "", EmployeesName ?? "", Status);
            }
            catch (Exception ex)
            {
                return await Error("生产领料-分页获取", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据生产领料编号和仓库编号获取生产领料明细表方法
        /// </summary>
        /// <param name="OrderProductPickId">生产领料编号</param>
        /// <param name="WareHouseId">仓库编号</param>
        /// <returns></returns>
        [HttpGet("GetOrderProductPickbyId")]
        public async Task<IActionResult> GetOrderProductPickbyId([FromQuery] string OrderProductPickId, [FromQuery] string WareHouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetOrderProductPickbyIdAsync(OrderProductPickId, WareHouseId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("生产领料-获取生产领料明细表", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 新增生产领料方法
        /// </summary>
        /// <param name="model">生产领料模型</param>
        /// <param name="OrderProductPickItemString">生产领料明细表模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] OrderProductPick model, [FromForm] string OrderProductPickItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderProductPickItem> list = new List<OrderProductPickItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderProductPickItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderProductPickItem>>(OrderProductPickItemString);
                    list.ForEach(x =>
                    {
                        x.OrderProductPickId = model.Id;
                        x.Creator = User.Identity.Name;
                    });
                }

                model.Creator = HttpContext.User.Identity.Name;

                var isSuccess = await Services.AddAsync(model, list);
                if (isSuccess)
                    status.Msg = "新增成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("生产领料-新增", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 修改生产领料方法
        /// </summary>
        /// <param name="model">生产领料模型</param>
        /// <param name="OrderProductPickItemString">生产领料明细表模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] OrderProductPick model, [FromForm] string OrderProductPickItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderProductPickItem> list = new List<OrderProductPickItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderProductPickItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderProductPickItem>>(OrderProductPickItemString);
                    list.ForEach(x =>
                    {
                        x.Creator = User.Identity.Name;
                        x.OrderProductPickId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = HttpContext.User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                    status.Msg = "修改成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("生产领料-修改", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 批量删除生产领料方法
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                    status.Msg = "删除成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("生产领料-批量删除", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 删除生产领料方法
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                    status.Msg = "删除成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("生产领料-删除", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据仓库编号和产品编号查询BOM组成方法
        /// </summary>
        /// <param name="WareHouseId">仓库编号</param>
        /// <param name="ItemId">产品编号</param>
        /// <returns></returns>
        [HttpGet("GetBomItembyId")]
        public async Task<IActionResult> GetBomItembyId(string WareHouseId, string ItemId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetBomItembyId(WareHouseId, ItemId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("生产领料-查询BOM组成", ex);
            }
            return Ok(status);
        } 
        
        /// <summary>
        /// 修改单据状态
        /// </summary>
        /// <param name="Id">单据Id</param>
        /// <param name="Status">状态：0待审核 1已审核</param>
        /// <returns></returns>
        [HttpPut("UpdateStatus")]
        public async Task<IActionResult> UpdateStatus([FromForm]long Id, [FromForm] int Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.UpdateStatus(Id, Status);
            }
            catch (Exception ex)
            {
                return await Error("生产领料-修改单据状态", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {
                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[]
                {
                    new ReportDomain{Title="序号",Fileld="No"},
                    new ReportDomain{Title="领料编号",Fileld="Number"},
                    new ReportDomain{Title="领料工单编号",Fileld="WorkorderCode"},
                    new ReportDomain{Title="领料仓库",Fileld="WaarehouseId"},
                    new ReportDomain{Title="经办人",Fileld="EmpolyeesName"},
                    new ReportDomain{Title="制单人",Fileld="Creator"},
                    new ReportDomain{Title="领料日期",Fileld="PickDate"},
                    new ReportDomain{Title="创建日期",Fileld="CreateTime"},
                    new ReportDomain{Title="状态",Fileld="Status"},
                    new ReportDomain{Title="备注",Fileld="Remark"}
                };
                var fileArray = BaseReport.Export(list, "生产领料信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "生产领料信息.xls");
            }
            catch(Exception ex)
            {
                await LogHelper.WriteErrorLog("生产领料-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }
        }
        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="ExString"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        private async Task<IActionResult> Error(string ExString, Exception ex)
        {
            var status = BaseStatus.CreateInstance();
            status.Code = -1;
            status.Msg = "服务器异常，请稍后重试";
            //写日志
            await LogHelper.WriteErrorLog(ExString, ex, HttpContext);
            return new ObjectResult(status) { StatusCode = StatusCodes.Status500InternalServerError };
        }
    }
}
